<template>
    <div class="copyEntry">
        <!-- 复制 -->
        <el-dialog title="复制" :visible.sync="dialogVisible" width="90%" top="5vh" custom-class="import-dialog" :close-on-click-modal="false">
            <div class="content">
                <div class="leftContent">
                    <HeaderTitle>
                        <div slot="title">产品信息</div>
                    </HeaderTitle>
                    <div class="leftContent-product">
                        <el-input placeholder="产品代码/名称" v-model="filterText" size="mini"></el-input>
                        <el-tree
                            class="filter-tree"
                            :data="treeData"
                            :props="defaultProps"
                            default-expand-all
                            :expand-on-click-node="false"
                            :filter-node-method="filterNode"
                            highlight-current
                            ref="tree"
                            style="margin-top: 5px"
                            @node-click="handleNodeClick"
                        >
                            <span slot-scope="{ node }">
                                <span :title="node.label">{{ node.label }}</span>
                            </span>
                        </el-tree>    
                    </div>
                    <HeaderTitle>
                        <div slot="title">规则分类</div>
                    </HeaderTitle>
                    <yh-tree
                        class="filter-tree1"
                        :data="treeTypeData"
                        :props="defaultProps"
                        :expand-on-click-node="false"
                        default-expand-all
                        highlight-current
                        ref="tree1"
                        @node-click="handleTypeClick"
                    >
                        <span slot-scope="{ node }">
                            <span :title="node.label">{{ node.label }}</span>
                        </span>
                    </yh-tree>
                </div>
                <div class="rightContent">
                    <HeaderTitle>
                        <div slot="title">规则列表</div>
                    </HeaderTitle>
                    <div style="margin: 10px 10px;">
                        <el-input
                            v-model="selectData.entryNameLike"
                            placeholder="请输入规则编号或说明"
                            size="small"
                            style="width: 300px;"
                        >
                        </el-input>
                        <el-button type="primary" @click="getRiskEntry(paging, sorter, selectData)" size="mini">查询</el-button>    
                    </div>
                    <el-table
                        :data="tableData"
                        tooltip-effect="dark"
                        style="width: 99%; min-height: 420px; margin: 0 auto"
                        border
                        ref="table"
                        size="mini" 
                        height="420px"
                        :auto-resize="true"
                        v-loading="tabloading"
                        @selection-change="handleSelectionChange"
                        @checkbox-all="handleSelectionChange"
                        @sort-change="handleSort"
                        :default-sort="{ prop: sortProp, order: sortOrder }"
                    >
                        <el-table-column type="selection" width="55"></el-table-column>
                        <el-table-column label="规则编号" width="120" prop="entryCode" fixed="left" sortable="custom" show-overflow-tooltip>
                            <template slot-scope="scope">
                                <span v-if="scope.row.modifyType === '2' && scope.row.modifyStatus === '1'">
                                    <i class="el-icon-setting" />{{ scope.row.entryCode }}
                                </span>
                                <span v-else-if="scope.row.modifyType === '3' && scope.row.modifyStatus === '1'">
                                    <i class="el-icon-delete" />{{ scope.row.entryCode }}
                                </span>
                                <span v-else-if="scope.row.modifyType === '1' && scope.row.modifyStatus === '1'">
                                    <i class="el-icon-folder-add" />{{ scope.row.entryCode }}
                                </span>
                                <span v-else>
                                    {{ scope.row.entryCode }}
                                </span>
                            </template>
                        </el-table-column>

                        <el-table-column
                            v-for="(col, index) in Columns"
                            :key="index"
                            :prop="col.prop"
                            :label="col.title"
                            :width="col.width"
                            :min-width="col.minWidth || '105px'"
                            show-overflow-tooltip
                            :sortable="col.sortable?'custom': false"
                        >
                            <template slot-scope="scope">
                                <span v-if="['thresholdValue1', 'thresholdValue2', 'thresholdValue3'].includes(col.prop)" style="float:right;">
                                    {{ scope.row[col.prop] ? thresholdTypeFormat(scope.row[col.prop], scope.row.unit) : '' }}
                                </span>

                                <span v-else v-html="getTbalesData(scope.row, col.prop)"></span>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="block">
                        <risk-pagination :paging="paging" @page-change="pageRet"></risk-pagination>
                    </div>    
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="sendBatchAddRelations">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Watch, Prop } from 'vue-property-decorator';
import HeaderTitle from '../commom/header-title.vue';
import RiskIconButton from '@/common/components/risk-icon-button.vue';
import RiskPagination from '@/common/components/risk-pagination.vue';
import DictionConstUtil, { SGU_CACHE } from '@/utils/diction-const-util';
import { UUID, timeFormat, numberFormat, unitShow } from '@/utils/tools';
export interface pages {
    total?: number;
    pageSize?: number;
    currentPage?: number;
}

@Component({
    name: 'CopyEntryDialog',
    components: {
        HeaderTitle,
        RiskIconButton,
        RiskPagination
    },
})
export default class CopyEntryDialog extends Vue {
    @Prop() copyEntryDialog;
    @Prop() indexClauseRelation; // 当前点击的条款
    @Prop() clauseCodesList; // 条款多选全部数据
    private dialogVisible: boolean = false;
    accountList: any[] = [];
    treeData: any[] = [
        // 条目列表
        {
            id: '-1',
            label: '全部选择',
            children: [],
        },
    ];
    treeTypeData: any[] = [
        // 风险类别
        {
            id: '-1',
            label: '全部选择',
            children: [],
        },
    ];
    paging: any = {
        total: 0,
        currentPage: 1,
        totalPage: 0,
        pageSize: 25,
    };
    sorter: any = {
        entryCode: 'descend',
    };
    sortProp: string = 'entryName';
    sortOrder: string = 'desc'; // 排序方式
    tabloading: boolean = false;
    multipleSelection = []; // 多选
    batchAddRelations = []; // 关联字段
    selectData: any = {
        entryCode: [], // 条目编号
        precision: false, // 准确搜索
        riskCalTypes: [], // 作用范围
        entryName: '', // 风险说明
        entryStatuss: [], // 启用状态
        controlGrades: [], // 风险等级
        beginDate: '', // 生效时间
        endDate: '', // 失效时间
        accountControlValue: [], // 基金账户
        sourceType: [], // 条目来源
        entryTypes: [], // 风险类型
        entryGroups: [], // 条目组
        excludeEntryGroup: false, // 排除选中
        customType: [], // 自定义分类
        checkUserCodes: '', // 复核人
        checkTableDataDirection: '', // 复核时间
        entryRoleCode: [], // 条目角色
        sort: '', // 排序字段
        fdAcCodeControlValue: [],
        assetCodeControlValue: [],
        entryNameLike: '', // 模糊查询
    };
    prams: any = {
        accountControlValue: [],
        entryTypes: [],
        sourceType: [],
    };
    filterText = '';
    defaultProps = {
      children: 'children',
      label: 'label'
    }
    tableData: any[] = [];
    private groupPage: pages = {
        currentPage: 1,
        pageSize: 50,
        total: 0,
    };
    // 排序字段
    sortParamObj = {
        entryName: 'C_ENTRY_NAME',
    };
    Columns: any[] = [
        {
            title: '风险说明',
            prop: 'entryName',
            minWidth: 250,
            tooltip: false,
            sortable: true
        },
        {
            title: '变动序号',
            prop: 'changeNo',
            tooltip: false,
        },
        {
            title: '风险类型',
            prop: 'entryType',
            minWidth: 130,
            tooltip: false,
        },
        {
            title: '生效日期',
            prop: 'beginDate',
        },
        {
            title: '失效日期',
            prop: 'endDate',
        },
        {
            title: '优先级',
            prop: 'level',
        },
        {
            title: '状态',
            prop: 'entryStatusValid',
        },
        {
            title: '风险等级',
            prop: 'controlGrade',
        },
        {
            title: '作用范围',
            prop: 'riskCalTypes',
        },
        {
            title: '阈值类型1',
            prop: 'thresholdType1',
            minWidth: 120,
        },
        {
            title: '阈值1',
            prop: 'thresholdValue1',
            minWidth: 150,
            funcBody: (value, record) => (value ? this.thresholdTypeFormat(value, record.unit) : ''),
        },
        {
            title: '阈值类型2',
            prop: 'thresholdType2',
            minWidth: 120,
        },
        {
            title: '阈值2',
            prop: 'thresholdValue2',
            minWidth: 150,
            funcBody: (value, record) => (value ? this.thresholdTypeFormat(value, record.unit) : ''),
        },
        {
            title: '阈值类型3',
            prop: 'thresholdType3',
            minWidth: 120,
        },
        {
            title: '阈值3',
            prop: 'thresholdValue3',
            minWidth: 150,
            funcBody: (value, record) => (value ? this.thresholdTypeFormat(value, record.unit) : ''),
        },
        {
            title: '比较方向',
            prop: 'compareType',
        },
        {
            title: '账户层次',
            prop: 'originalAccountId',
            minWidth: 150,
        },
        {
            title: '控制类型',
            prop: 'accountControlType',
            minWidth: 150,
        },
        {
            title: '控制账户',
            prop: 'accountControlValue',
            minWidth: 150,
        },
        {
            title: '排除账户',
            prop: 'accountDebarValue',
            minWidth: 120,
        },
        {
            title: '排除账户组',
            prop: 'accountGroupDebarValue',
            minWidth: 150,
        },

        {
            title: '修改日期',
            prop: 'modifyDate',
        },
        {
            title: '修改时间',
            prop: 'modifyTime',
        },
        {
            title: '修改人',
            prop: 'modifyUser',
            minWidth: 150,
        },
        {
            title: '规则来源',
            prop: 'sourceType',
        },
        {
            title: '自定义分类',
            prop: 'customType',
            minWidth: 140,
        },
        {
            title: '规则角色分类',
            prop: 'entryRoleCode',
            minWidth: 180,
            tooltip: false,
        },
    ];
    @Watch('copyEntryDialog')
    watchCopyEntryDialog(val) {
        this.dialogVisible = val;
        if (val == true) {
            this.getAllData();
        }
    }
    @Watch('dialogVisible')
    watchDialogVisible(val) {
        if (val == false) {
            this.$emit('emitCopyEntryDialog', val, '')    
        }
    }
    async getAllData() {
        this.getRiskEntry(this.paging, this.sorter, this.prams);
        // 条目数据
        let fubds = await SGU_CACHE('FundInfoByUser', '/fundInfo/list/byUser/like', []);
        let local = [];
        for (let itme of fubds) {
            let datas = itme.fundCode + '-' + itme.fundName;
            local.push({ label: datas, id: itme.fundCode });
        }
        // 基金账户
        this.accountList = local;
        this.treeData[0].children = local;

        // 风险类别数据
        let entryType = await SGU_CACHE('EntryType', '/entry/entryType', []);
        let typeLocal = [];
        for (let itme of entryType) {
            let datas = itme.entryTypeId + ' ' + itme.entryTypeName;
            typeLocal.push({ label: datas, id: itme.entryTypeId });
        }
        this.treeTypeData[0].children = typeLocal;
    }
    thresholdTypeFormat(value, unit): string {
        // 三目运算符, unit为'%'和'万元'、'万股'的由后端处理了，不由numberFormat方法处理
        return ['%', '万元', '万股'].includes(unit) ? value : numberFormat(value.replace(/[^0-9.]/gi, ''), unit) + unitShow(unit);
    }
    // 处理table中的数据
    getTbalesData(data: any, props: any) {
        // 自定义风险分类
        let datas = data[props];
        if (props == 'entryType') {
            // eslint-disable-next-line no-unused-expressions
            return DictionConstUtil.EntryType[datas];
        } else if (props == 'entryStatusValid') {
            if (data[props] == true) {
                let span = '<span style="color:green">启用</span>';
                return span;
            } else {
                let span = '<span style="color:red">禁用</span>';
                return span;
            }
        } else if (props == 'sourceType') {
            return DictionConstUtil.SourceType[datas];
        } else if (props == 'beginDate') {
            if (datas == '0') {
                return '';
            } else {
                return datas;
            }
        } else if (props == 'endDate') {
            if (datas == '0') {
                return '';
            } else {
                return datas;
            }
        } else if (props == 'modifyTime') {
            return timeFormat(datas);
        } else {
            return datas;
        }
    }
    // 产品查询
    handleNodeClick(val: any): void {
        this.selectData.accountControlValue = [];
        if (val.id != '-1') {
           this.selectData.accountControlValue.push(val.id);  
        }
        this.getRiskEntry(this.paging, this.sorter, this.selectData);
    }
    // 风险类别查询
    handleTypeClick(val: any): void {
        this.selectData.entryTypes = [];
        this.selectData.entryTypes.push(String(val.id));
        this.getRiskEntry(this.paging, this.sorter, this.selectData);
    }
    // 获取条目列表
    getRiskEntry(paging: any, sorter: any, selectData: any): void {
        this.tabloading = true;
        this.$axios.post('/entry/list/handled', {
            paging: paging,
            sorter: sorter,
            riskEntryControlQuery: selectData,
        }).then((res: any) => {
            res.list.map((item: any) => {
                item.key = item.entryCode;
                return item;
            });
            this.paging.total = res.total;
            this.tableData = res.list;
            this.tabloading = false;
            // this.onChangselectedFieldList();
        }).catch(() => {
            this.paging.total = 0;
            this.tableData = [];
            this.tabloading = false;
        });
    }
    // 分页
    private pageRet(): void {
        // this.paging.currentPage = this.groupPage.currentPage;
        // this.paging.pageSize = this.groupPage.pageSize;
        this.getRiskEntry(this.paging, this.sorter, this.selectData);
    }
    // 表头排序
    handleSort(column: any) {
        this.sortProp = column.prop;
        this.sortOrder = column.order;
        const sortType = column.order == 'ascending' ? 'ASC' : column.order == 'descending' ? 'DESC' : '';
        let sort = '';
        const prop = column.prop;
        if (sortType) {
            if (prop == 'entryCode') {
                if (sortType == 'DESC') {
                    sort = "TO_NUMBER(REGEXP_REPLACE(C_ENTRY_CODE,'[^0-9]','')) DESC";
                } else {
                    sort = "TO_NUMBER(REGEXP_REPLACE(C_ENTRY_CODE,'[^0-9]','')) ASC";
                }
            } else {
                sort = this.sortParamObj[prop] + ' ' + sortType;
            }
        }
        this.selectData.sort = sort;
        this.getRiskEntry(this.paging, this.sorter, this.selectData);
    }
    // 多选
    handleSelectionChange(val) {
        this.multipleSelection = val;
    }
    // 确认关联
    sendBatchAddRelations() {
        if (this.multipleSelection.length == 0) {
            this.yh_message_warn('关联条目不可为空！');
            return
        }
        this.batchAddRelations = []
        if (this.clauseCodesList.length == 0) {
            this.multipleSelection.forEach(item => {
                this.batchAddRelations.push({
                    clauseCode: this.indexClauseRelation.clauseCode,
                    entryCode: item.entryCode
                })
            })    
        } else {
            for (let i = 0; i < this.clauseCodesList.length; i++) {
                if (this.clauseCodesList[i].modifyEvent == '1') {
                    this.yh_message_warn('所选条款存在未复核！');
                    return
                }
            }
            this.multipleSelection.forEach(item => {
                this.clauseCodesList.forEach(item2 => {
                    this.batchAddRelations.push({
                        clauseCode: item2.clauseCode,
                        entryCode: item.entryCode
                    })
                })
            })   
        }
        this.$axios.post('/indexClauseRelation/batchAddRelations', this.batchAddRelations).then((res: any) => {
            this.yh_message_success('关联成功！')
            this.$emit('emitCopyEntryDialog', false, '确认关联')
            this.dialogVisible = false;
        })
    }
    filterChangeEvent() {}
    @Watch('filterText')
    handleDataSource(val) {
        (this.$refs.tree as any).filter(val);
    }
    filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
    }
}
</script>
<style lang="scss" scoped>
.copyEntry {
    background: #ffffff;
}
.content{
    display: flex;
    overflow: hidden;
    .leftContent{
        width: 220px;
        height: 100%;
        padding-right: 3px;
        border-right: 1px solid #e5e5e5;
        .leftContent-product{
            margin-top: 10px;
            
        }
    }
    .el-tree{
        border: 1px solid #dcdfe6;
        height: 29vh;
        overflow: auto;
        padding-top: 5px;
    }
    .rightContent{
        width: calc(100% - 220px);
    }
}
/deep/ .el-dialog .el-dialog__body{
    height: 76vh !important;
    padding: 0px 10px 10px 10px !important;
    max-height: 76vh;
}
</style>
